﻿using Microsoft.AspNetCore.Http;
using System.Text.Json;

namespace HMS.Common.AspNetCore;

public class MultiTenantMiddleware
{
    private readonly RequestDelegate _next;

    public MultiTenantMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            context.Response.ContentType = "application/problem+json";

            context.Response.StatusCode = StatusCodes.Status500InternalServerError;

            if (ex.Message.Contains("对象名") && ex.Message.Contains("无效"))
            {
                await JsonSerializer.SerializeAsync(
                context.Response.Body,
                "请联系服务提供商生成数据存储中心",
                new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
            }
            else
            {
                await JsonSerializer.SerializeAsync(
                context.Response.Body,
                ex.Message,
                new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
            }
        }
    }
}